package tianqi.service.shop.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import tianqi.Dao.product.ProductDetailDao;
import tianqi.entity.ProductCon;
import tianqi.entity.ShopCar;
import tianqi.service.shop.ShopCarService;
import tianqi.utils.StringUtils;

@Service
public class ShopCarServiceImpl implements ShopCarService {

	@Autowired
	private ProductDetailDao productDetailDao;

	@Override
	public String queryCar(HttpServletRequest req, HttpServletResponse res, Model m) {
		List<ShopCar> list = new ArrayList<ShopCar>();
		try {
			// 得到cookie数据
			Cookie[] cookies = req.getCookies();
			if (cookies != null || cookies.length > 0) {
				// 声明name 用来接收cookie中的key,value 用来接收cookie值
				String name = "", value = "";
				for (Cookie cookie : cookies) {
					name = cookie.getName();
					if (ShopCarService.COOKIE_NAME.equals(name)) {
						value = cookie.getValue();
						value = URLDecoder.decode(value, "UTF-8");
						System.out.println("value: " + value);
						JSONArray jArray = JSONArray.fromObject(value);
						// 创建json的配置对象
						JsonConfig jConfig = new JsonConfig();
						String[] excludes = { "pro", "detailImg" };
						// 排除 pro 这一属性
						jConfig.setExcludes(excludes);
						jConfig.setRootClass(ShopCar.class);
						list = (List<ShopCar>) JSONSerializer.toJava(jArray, jConfig);
						Map<String, String> map = new HashMap<String, String>();
						ProductCon selectByPrimaryKey = null;
						for (ShopCar car : list) {
							selectByPrimaryKey = productDetailDao.selectByPrimaryKey(car.getIdPro());
							car.setPro(selectByPrimaryKey);
							map.put("col", selectByPrimaryKey.getImgName());
							map.put("tab", selectByPrimaryKey.getTableName());
							map.put("idcol", selectByPrimaryKey.getColumn1());
							map.put("id", "'" + selectByPrimaryKey.getIdPro() + "'");
							car.setDetailImg(productDetailDao.queryDetailImg(map));

						}
						Integer proTotal = 0;
						BigDecimal bDecimal = new BigDecimal(0);
						for (ShopCar shopCar : list) {
							proTotal += Integer.valueOf(shopCar.getNum());
							bDecimal = bDecimal.add(new BigDecimal(shopCar.getNum())
									.multiply(new BigDecimal(shopCar.getPro().getYgPrice())));
						}
						m.addAttribute("queryCar", list);
						m.addAttribute("proTotal", proTotal);
						m.addAttribute("bDecimal", bDecimal);

					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			System.out.println("URLDecoder.decode(,);  方法抛出异常");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "shopCar";
	}
	@Override
	public List<ShopCar> queryCars(HttpServletRequest req, HttpServletResponse res) {
		List<ShopCar> list = new ArrayList<ShopCar>();
		try {
			// 得到cookie数据
			Cookie[] cookies = req.getCookies();
			if (cookies != null || cookies.length > 0) {
				// 声明name 用来接收cookie中的key,value 用来接收cookie值
				String name = "", value = "";
				for (Cookie cookie : cookies) {
					name = cookie.getName();
					if (ShopCarService.COOKIE_NAME.equals(name)) {
						value = cookie.getValue();
						value = URLDecoder.decode(value, "UTF-8");
						System.out.println("value: " + value);
						JSONArray jArray = JSONArray.fromObject(value);
						// 创建json的配置对象
						JsonConfig jConfig = new JsonConfig();
						String[] excludes = { "pro", "detailImg" };
						// 排除 pro 这一属性
						jConfig.setExcludes(excludes);
						jConfig.setRootClass(ShopCar.class);
						list = (List<ShopCar>) JSONSerializer.toJava(jArray, jConfig);
						Map<String, String> map = new HashMap<String, String>();
						ProductCon selectByPrimaryKey = null;
						for (ShopCar car : list) {
							selectByPrimaryKey = productDetailDao.selectByPrimaryKey(car.getIdPro());
							car.setPro(selectByPrimaryKey);
							map.put("col", selectByPrimaryKey.getImgName());
							map.put("tab", selectByPrimaryKey.getTableName());
							map.put("idcol", selectByPrimaryKey.getColumn1());
							map.put("id", "'" + selectByPrimaryKey.getIdPro() + "'");
							car.setDetailImg(productDetailDao.queryDetailImg(map));
							
						}
						
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			System.out.println("URLDecoder.decode(,);  方法抛出异常");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return list;
	}
	@Override
	public String checkStockAll(HttpServletRequest req) {
		List<ShopCar> list = new ArrayList<ShopCar>();
		String flag="true";
		try {
			// 得到cookie数据
			Cookie[] cookies = req.getCookies();
			if (cookies != null || cookies.length > 0) {
				// 声明name 用来接收cookie中的key,value 用来接收cookie值
				String name = "", value = "";
				for (Cookie cookie : cookies) {
					name = cookie.getName();
					if (ShopCarService.COOKIE_NAME.equals(name)) {
						value = cookie.getValue();
						value = URLDecoder.decode(value, "UTF-8");
						System.out.println("value: " + value);
						JSONArray jArray = JSONArray.fromObject(value);
						// 创建json的配置对象
						JsonConfig jConfig = new JsonConfig();
						String[] excludes = { "pro", "detailImg" };
						// 排除 pro 这一属性
						jConfig.setExcludes(excludes);
						jConfig.setRootClass(ShopCar.class);
						list = (List<ShopCar>) JSONSerializer.toJava(jArray, jConfig);
						Map<String, String> map = new HashMap<String, String>();
						ProductCon selectByPrimaryKey = null;
						for (ShopCar car : list) {
							map.put("id", "'"+car.getIdPro()+"'");
							map.put("spec", "'"+car.getSpec()+"'");
							selectByPrimaryKey = productDetailDao.queryDetailBySpec(map);
							if (Integer.valueOf(car.getNum())>selectByPrimaryKey.getSpecOne().getStock()) {
								flag=selectByPrimaryKey.getProCall()+" 规格为: "+selectByPrimaryKey.getSpecOne().getSpec()+" 库存不足 "+car.getNum()+" 件";
							}
							
						}
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			System.out.println("URLDecoder.decode(,);  方法抛出异常");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return flag;
	}

	@Override
	public void addCar(String id, String num, String spec, HttpServletRequest req, HttpServletResponse res) {
		List<ShopCar> list = new ArrayList<ShopCar>();

		// 创建json的配置对象
		JsonConfig jConfig = new JsonConfig();
		// 排除 pro detailImg这一属性
		String[] excludes = { "pro", "detailImg" };
		jConfig.setExcludes(excludes);
		jConfig.setRootClass(ShopCar.class);
		try {
			// 得到cookie数据
			Cookie[] cookies = req.getCookies();
			if (cookies != null || cookies.length > 0) {
				// 声明name 用来接收cookie中的key,value 用来接收cookie值
				String name = "", value = "";
				for (Cookie cookie : cookies) {
					name = cookie.getName();
					if (ShopCarService.COOKIE_NAME.equals(name)) {
						value = cookie.getValue();
						value = URLDecoder.decode(value, "UTF-8");
						System.out.println("value: " + value);
						JSONArray jArray = JSONArray.fromObject(value);

						list = (List<ShopCar>) JSONSerializer.toJava(jArray, jConfig);
//						Map<String, String> map = new HashMap<String, String>();
//						ProductCon selectByPrimaryKey = null;
//						for (ShopCar car : list) {
//							selectByPrimaryKey = productDetailDao.selectByPrimaryKey(car.getIdPro());
//							car.setPro(selectByPrimaryKey);
//							map.put("col", selectByPrimaryKey.getImgName());
//							map.put("tab", selectByPrimaryKey.getTableName());
//							map.put("idcol", selectByPrimaryKey.getColumn1());
//							map.put("id", "'" + selectByPrimaryKey.getIdPro() + "'");
//							car.setDetailImg(productDetailDao.queryDetailImg(map));
//
//						}
						boolean flag = false;
						for (ShopCar shopCar : list) {
							if (shopCar.getIdPro().equals(id) && shopCar.getSpec().equals(spec)) {
								shopCar.setNum(num);
								flag = true;
								break;
							}
						}
						if (!flag) {
							ShopCar shopCar = new ShopCar();
							shopCar.setIdPro(id);
							shopCar.setNum(num);
							shopCar.setSpec(spec);
							list.add(shopCar);
						}

					}
				}
			}

			if (list.size() == 0) {
				ShopCar shopCar = new ShopCar();
				shopCar.setIdPro(id);
				shopCar.setNum(num);
				shopCar.setSpec(spec);
				list.add(shopCar);
			}
			JSONArray jArray = JSONArray.fromObject(list, jConfig);
			String encode = URLEncoder.encode(jArray.toString(), "UTF-8");
			Cookie cookie = new Cookie(ShopCarService.COOKIE_NAME, encode);
			cookie.setMaxAge(Integer.MAX_VALUE);
			cookie.setPath("/");
			res.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			System.out.println("URLDecoder.decode(,);  方法抛出异常");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public Integer querySpec(Map m) {
		return productDetailDao.querySpecByPrimaryKey(m);
	}

	@Override
	public void addNum(String id, String num, String spec, HttpServletRequest req, HttpServletResponse res) {

		List<ShopCar> list = new ArrayList<ShopCar>();

		// 创建json的配置对象
		JsonConfig jConfig = new JsonConfig();
		String[] excludes = { "pro", "detailImg" };
		// 排除 pro 这一属性
		jConfig.setExcludes(excludes);
		jConfig.setRootClass(ShopCar.class);
		try {
			// 得到cookie数据
			Cookie[] cookies = req.getCookies();
			if (cookies != null || cookies.length > 0) {
				// 声明name 用来接收cookie中的key,value 用来接收cookie值
				String name = "", value = "";
				for (Cookie cookie : cookies) {
					name = cookie.getName();
					if (ShopCarService.COOKIE_NAME.equals(name)) {
						value = cookie.getValue();
						value = URLDecoder.decode(value, "UTF-8");
						System.out.println("value: " + value);
						JSONArray jArray = JSONArray.fromObject(value);

						list = (List<ShopCar>) JSONSerializer.toJava(jArray, jConfig);
						boolean flag = false;
						for (ShopCar shopCar : list) {
							if (shopCar.getIdPro().equals(id) && shopCar.getSpec().equals(spec)) {
								shopCar.setNum(num);
								flag = true;
								break;
							}
						}
						if (!flag) {
							ShopCar shopCar = new ShopCar();
							shopCar.setIdPro(id);
							shopCar.setNum(num);
							shopCar.setSpec(spec);
							list.add(shopCar);
						}

					}
				}
			}

			if (list.size() == 0) {
				ShopCar shopCar = new ShopCar();
				shopCar.setIdPro(id);
				shopCar.setNum(num);
				shopCar.setSpec(spec);
				list.add(shopCar);
			}
			JSONArray jArray = JSONArray.fromObject(list, jConfig);
			String encode = URLEncoder.encode(jArray.toString(), "UTF-8");
			Cookie cookie = new Cookie(ShopCarService.COOKIE_NAME, encode);
			cookie.setMaxAge(Integer.MAX_VALUE);
			cookie.setPath("/");
			res.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			System.out.println("URLDecoder.decode(,);  方法抛出异常");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void deleteCar(String id,String spec, HttpServletRequest req, HttpServletResponse res) {

		List<ShopCar> list = new ArrayList<ShopCar>();

		// 创建json的配置对象
		JsonConfig jConfig = new JsonConfig();
		String[] excludes = { "pro", "detailImg" };
		// 排除 pro 这一属性
		jConfig.setExcludes(excludes);
		jConfig.setRootClass(ShopCar.class);
		try {
			// 得到cookie数据
			Cookie[] cookies = req.getCookies();
			if (cookies != null || cookies.length > 0) {
				// 声明name 用来接收cookie中的key,value 用来接收cookie值
				String name = "", value = "";
				for (Cookie cookie : cookies) {
					name = cookie.getName();
					if (ShopCarService.COOKIE_NAME.equals(name)) {
						value = cookie.getValue();
						value = URLDecoder.decode(value, "UTF-8");
						System.out.println("value: " + value);
						JSONArray jArray = JSONArray.fromObject(value);

						list = (List<ShopCar>) JSONSerializer.toJava(jArray, jConfig);
						for (int i = 0; i < list.size(); i++) {
							if (list.get(i).getIdPro().equals(id) && list.get(i).getSpec().equals(spec)) {
								list.remove(i);
								break;
							}
						}

					}
				}
			}

			JSONArray jArray = JSONArray.fromObject(list, jConfig);
			String encode = URLEncoder.encode(jArray.toString(), "UTF-8");
			Cookie cookie = new Cookie(ShopCarService.COOKIE_NAME, encode);
			cookie.setMaxAge(Integer.MAX_VALUE);
			cookie.setPath("/");
			res.addCookie(cookie);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	@Override
	public void clearCar(HttpServletRequest req, HttpServletResponse res) {
		
		List<ShopCar> list = new ArrayList<ShopCar>();
		
		// 创建json的配置对象
		JsonConfig jConfig = new JsonConfig();
		String[] excludes = { "pro", "detailImg" };
		// 排除 pro 这一属性
		jConfig.setExcludes(excludes);
		jConfig.setRootClass(ShopCar.class);
		try {
			// 得到cookie数据
			Cookie[] cookies = req.getCookies();
			if (cookies != null || cookies.length > 0) {
				// 声明name 用来接收cookie中的key,value 用来接收cookie值
				String name = "", value = "";
				for (Cookie cookie : cookies) {
					name = cookie.getName();
					if (ShopCarService.COOKIE_NAME.equals(name)) {
						value = cookie.getValue();
						value = URLDecoder.decode(value, "UTF-8");
						System.out.println("value: " + value);
						JSONArray jArray = JSONArray.fromObject(value);
						
						list = (List<ShopCar>) JSONSerializer.toJava(jArray, jConfig);
						list.clear();
						
					}
				}
			}
			
			JSONArray jArray = JSONArray.fromObject(list, jConfig);
			String encode = URLEncoder.encode(jArray.toString(), "UTF-8");
			Cookie cookie = new Cookie(ShopCarService.COOKIE_NAME, encode);
			cookie.setMaxAge(Integer.MAX_VALUE);
			cookie.setPath("/");
			res.addCookie(cookie);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public Map<String, String> queryCarNum(HttpServletRequest req, HttpServletResponse res) {
		List<ShopCar> list = new ArrayList<ShopCar>();
		Map<String, String> map2=new HashMap<String,String>();
		try {
			// 得到cookie数据
			Cookie[] cookies = req.getCookies();
			if (cookies != null || cookies.length > 0) {
				// 声明name 用来接收cookie中的key,value 用来接收cookie值
				String name = "", value = "";
				for (Cookie cookie : cookies) {
					name = cookie.getName();
					if (ShopCarService.COOKIE_NAME.equals(name)) {
						value = cookie.getValue();
						value = URLDecoder.decode(value, "UTF-8");
						System.out.println("value: " + value);
						JSONArray jArray = JSONArray.fromObject(value);
						// 创建json的配置对象
						JsonConfig jConfig = new JsonConfig();
						String[] excludes = { "pro", "detailImg" };
						// 排除 pro 这一属性
						jConfig.setExcludes(excludes);
						jConfig.setRootClass(ShopCar.class);
						list = (List<ShopCar>) JSONSerializer.toJava(jArray, jConfig);
//						Map<String, String> map = new HashMap<String, String>();
						ProductCon selectByPrimaryKey = null;
						for (ShopCar car : list) {
							selectByPrimaryKey = productDetailDao.selectByPrimaryKey(car.getIdPro());
							car.setPro(selectByPrimaryKey);

						}
						Integer proTotal = 0;
						BigDecimal bDecimal = new BigDecimal(0);
						for (ShopCar shopCar : list) {
							proTotal += Integer.valueOf(shopCar.getNum());
							bDecimal = bDecimal.add(new BigDecimal(shopCar.getNum())
									.multiply(new BigDecimal(shopCar.getPro().getYgPrice())));
						}
						
						map2.put("proTotal", proTotal.toString());
						map2.put("bDecimal", bDecimal.toString());
						
						
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			System.out.println("URLDecoder.decode(,);  方法抛出异常");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return map2;
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
